package com.finder.im.tcp;

import com.finder.im.codec.config.BootstrapConfig;
import com.finder.im.tcp.reciver.MessageReciver;
import com.finder.im.tcp.redis.RedisManager;
import com.finder.im.tcp.register.RegistryZK;
import com.finder.im.tcp.register.ZKit;
import com.finder.im.tcp.server.LimServer;

import com.finder.im.tcp.server.LimWebSocketServer;
import com.finder.im.tcp.utils.MqFactory;
import org.I0Itec.zkclient.ZkClient;
import org.yaml.snakeyaml.Yaml;

import javax.validation.spi.BootstrapState;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Starter {
    public static void main(String[] args) {
        if (args.length > 0) {
            start(args[0]);
        }
    }

    private static void start(String path) {
        try {
            //读取配置信息
            FileInputStream inputStream = new FileInputStream(path);
            Yaml yaml = new Yaml();
            BootstrapConfig bootstrapConfig = yaml.loadAs(inputStream, BootstrapConfig.class);
            //创建serverSocket对象，等待接收连接
            new LimServer(bootstrapConfig.getLim()).start();
            //创建websocket对象等待接收连接
            new LimWebSocketServer(bootstrapConfig.getLim()).start();

            //初始化redis管理工具
            RedisManager.init(bootstrapConfig);
            //初始化mq管理工具
            MqFactory.init(bootstrapConfig.getLim().getRabbitmq());
            //初始化消息管理工具
            MessageReciver.init(bootstrapConfig.getLim().getBrokerId()+"");
            //注册im-core节点到zk
            registerZK(bootstrapConfig);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(500);
        }
    }

    public static void registerZK(BootstrapConfig config) throws UnknownHostException {
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        ZkClient zkClient = new ZkClient(config.getLim().getZkConfig().getZkAddr(),
                config.getLim().getZkConfig().getZkConnectTimeOut());
        ZKit zKit = new ZKit(zkClient);
        RegistryZK registryZK = new RegistryZK(zKit, hostAddress, config.getLim());
        new Thread(registryZK).start();
    }
}
